package com.lgj.mall.ware.service.impl;

import com.lgj.mall.common.constant.WareConstant;
import com.lgj.mall.ware.entity.PurchaseDetailEntity;
import com.lgj.mall.ware.service.PurchaseDetailService;
import com.lgj.mall.ware.service.WareSkuService;
import com.lgj.mall.ware.vo.MergeVO;
import com.lgj.mall.ware.vo.PurchaseDetailVo;
import com.lgj.mall.ware.vo.PurchaseDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lgj.mall.common.utils.PageUtils;
import com.lgj.mall.common.utils.Query;

import com.lgj.mall.ware.dao.PurchaseDao;
import com.lgj.mall.ware.entity.PurchaseEntity;
import com.lgj.mall.ware.service.PurchaseService;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {
    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceivePage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
                        .eq("status", 0)        //新建
                        .or().eq("status", 1)   //已分配
        );
        return new PageUtils(page);
    }

    @Override
    public void merge(MergeVO mergeVO) {
        //采购单如果空就创建,否则就合并
        Long purchaseId = mergeVO.getPurchaseId();
        //1.创建采购单
        if(purchaseId == null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(null);
            purchaseEntity.setUpdateTime(null);
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }
        // 确认采购单状态是0,1才可以合并
        List<Long> items = mergeVO.getItems();
        Collection<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listByIds(items);

        purchaseDetailEntities.forEach((item) -> {
            if (!item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode())
                    && !item.getStatus().equals(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode())) {
                throw new IllegalArgumentException("正在采购，无法进行分配");
            }
        });
        //2.合并采购需求
        //Lambda 必须用 final/effectively final 变量
        //有效 final（effectively final）”的概念：
        // 如果一个变量在初始化之后 没有再被赋值过，那么即使你没有写 final，编译器也会把它当成 final。
        Long finalPurchaseId = purchaseId;
        List<PurchaseDetailEntity> list = items.stream().map(id-> {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            purchaseDetailEntity.setId(id);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);  //设置采购单
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGED.getCode());//修改状态
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //按照id 更新
        purchaseDetailService.updateBatchById(list);

        //更新采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public void receive(List<Long> ids) {
        //只能领取状态为新建,已分配的采购单
        List<PurchaseEntity> list = ids.stream().map(id -> {
            PurchaseEntity byId = this.getById(id);
            return byId;
        }).filter(Objects::nonNull) // 过滤掉 null
        .filter(entity -> {
            if (entity.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || entity.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGED.getCode()) {
                return true;
            }
            return false;   //d否则无法过滤
        }).map(entity -> {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //设置更新时间和状态
            purchaseEntity.setId(entity.getId());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            return purchaseEntity;
        }).collect(Collectors.toList());

        //更新采购单
        this.updateBatchById(list);

        //更新采购项
        for(Long id:ids){
            //找对应的采购项
            List<PurchaseDetailEntity> detailEntities = purchaseDetailService.listDetailByPurchaseId(id);
            //更新
            List<PurchaseDetailEntity> collect = detailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());

            purchaseDetailService.updateBatchById(collect);
        }
    }

    @Override
    public void done(PurchaseDoneVo purchaseDoneVo) {
        Long purchaseId = purchaseDoneVo.getId();
        List<PurchaseDetailVo> items = purchaseDoneVo.getItems();
        boolean flag=true;  //如果采购项有一个失败,则采购单失败
        ArrayList<PurchaseDetailEntity> entities = new ArrayList<>();
        for(PurchaseDetailVo item:items){
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            //采购项目:异常
            if(item.getStatus()==WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag=false;
                detailEntity.setStatus(item.getStatus());
            }//正常状态
            else{
                Long detailId = item.getItemId();
                detailEntity.setId(detailId);
                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //入库(有:修改库存,无就添加)
                PurchaseDetailEntity entity = purchaseDetailService.getById(detailId);
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
            }
            entities.add(detailEntity);
        }
        //批量更新
        purchaseDetailService.updateBatchById(entities);
        //改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}